<template>
  <div class="theme-color-picker-wrapper">
    设置主题色：
    <ColorPicker v-model="themeColor"  @on-change="handleChangeThemeColor" alpha />
  </div>
</template>

<script>
export default {
  name: 'ThemeColorPicker',
  data() {
    return {
      themeColor: localStorage.getItem('iview_less_theme_color') || 'rgba(45, 140, 240, 1)'
    }
  },
  mounted() {
    this.handleChangeThemeColor(this.themeColor)
  },
  methods: {
    /**
     * 颜色选择器：主题色改变时触发
     * @param {string} rgbaNumber 色值，格式 hex，例如 #ffffff
     */
    handleChangeThemeColor(color) {
      localStorage.setItem('iview_less_theme_color', color)
      const rgbaNumber = color
        .replace('rgba(', '')
        .replace(')', '')
        .split(',')
      let themeObj = {
        theme: [...rgbaNumber].map(Number), //  主题原色
        fade90: [...rgbaNumber].map(Number), // 90% 透明
        fade20: [...rgbaNumber].map(Number), // 20% 透明
        shade5: [...rgbaNumber].map(Number), // 与黑色混合 5%
        tint20: [...rgbaNumber].map(Number), // 与白色混合 20%
        tint80: [...rgbaNumber].map(Number), // 与白色混合 80%
        tint90: [...rgbaNumber].map(Number) //  与白色混合 90%
      }
      themeObj.fade90[3] = 0.9
      themeObj.fade20[3] = 0.2
      // 转换rgb三个数值
      for (let i = 0; i < 3; i++) {
        themeObj.shade5[i] = Math.ceil(themeObj.shade5[i] - themeObj.shade5[i] * 0.05)
      }
      // 转换rgb三个数值
      for (let i = 0; i < 3; i++) {
        themeObj.tint20[i] = Math.ceil(themeObj.tint20[i] + 255 * 0.2 - themeObj.tint20[i] * 0.2)
        themeObj.tint80[i] = Math.ceil(themeObj.tint80[i] + 255 * 0.8 - themeObj.tint80[i] * 0.8)
        themeObj.tint90[i] = Math.ceil(themeObj.tint90[i] + 255 * 0.9 - themeObj.tint90[i] * 0.9)
      }
      for (let key in themeObj) {
        document.body.style.setProperty('--' + key, 'rgba(' + themeObj[key].join() + ')')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.theme-color-picker-wrapper {
  margin-bottom: 16px;
}
</style>
